<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>防火墙规则管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
    <script src="/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <blockquote class="layui-elem-quote layui-text">
            帮助中心:1. <a href="#" target="_blank">waf规则帮助文档</a>
            <a class="layui-btn" style="float:right" href="javascript:location.replace(location.href);" title="刷新">
              <i class="layui-icon">&#xe669;</i></a>
        </blockquote>
        <fieldset class="table-search-fieldset">
            <legend>搜索</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">应用名</label>
                            <div class="layui-input-inline">
                                <input type="text" name="appname" autocomplete="off" lay-verify="required" lay-reqtext="不能为空" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn"  lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <table class="layui-table" id="currentTableId" lay-filter="currentTableFilter"></table>
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="Add"><i class="layui-icon">&#xe61f;</i>添加规则</button>
            </div>
        </script>
        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>
    </div>
    	<!-- 弹添加框-->
  	<div class="layui-row" id="AddRuleInfo" style="display:none;margin: 40px 40px 40px 40px">
        <blockquote class="layui-elem-quote layui-text">
            <span style="color:red">防火墙规则添加说明:</span><br>1.应用包含三个级别,sys:表示应用到全网的规则,default:默认规则,用于接入应用时拷贝的规则,baidu-bbs:只应用到论坛的规则<br>
            2.规则类型：选择过滤请求头中的哪部分。<br>3.备注：标记此条规则的用途。
        </blockquote>
          <form class="layui-form layui-form-pane" action="">
              <div class="layui-form-item" pane="">
                  <div class="layui-inline">
                      <label class="layui-form-label">应用名</label>
                      <div class="layui-input-inline" style="width:400px">
                          <input type="text" name="appname" autocomplete="off" lay-verify="required" lay-reqtext="不能为空" class="layui-input">
                      </div>
                  </div>
              </div>
              <div class="layui-form-item" pane="">
                  <div class="layui-inline">
                      <label class="layui-form-label">规则类型</label>
                      <div class="layui-input-inline" style="width:400px">
                            <select name="ruletype" lay-filter="ruletype">
        	              			<option value="args" selected="">URL参数</option>
        	              			<option value="useragent">UserAgent</option>
        	              			<option value="cookie">Cookie</option>
        	              			<option value="post">POST内容</option>
        	              			<option value="url">URL</option>
        	              			<option value="whiteip">IP白名单</option>
        	              			<option value="blackip">IP黑名单</option>
        	              			<option value="whiteurl">URL白名单</option>
        	              			<option value="whiteua">UA白名单</option>
            		            </select>
                      </div>
                  </div>
              </div>
              <div class="layui-form-item" pane="">
                  <div class="layui-inline">
                      <label class="layui-form-label">规则</label>
                      <!--
                      <div class="layui-input-inline">
                          <input type="text" name="ruleitem" autocomplete="off" class="layui-input">
                      </div>
                      -->
                      <div class="layui-input-block">
                          <textarea name="ruleitem" style="height:147px;width:400px" class="layui-textarea" lay-verify="required" lay-reqtext="不能为空"></textarea>
                      </div>
                  </div>
              </div>
              <div class="layui-form-item" pane="">
                  <div class="layui-inline">
                      <label class="layui-form-label">备注</label>
                      <div class="layui-input-inline" style="width:400px">
                          <input type="text" name="remarks" autocomplete="off" class="layui-input">
                      </div>
                  </div>
              </div>
              <div class="layui-form-item">
                  <div class="layui-inline" style="margin-left:200px">
                      <button type="submit" class="layui-btn"  lay-submit lay-filter="Add"><i class="layui-icon">&#xe61f;</i>确认添加</button>
                  </div>
              </div>
          </form>
  	</div>
	<!-- 弹添加框end--> 
</div>
</body>
<script type="text/html" id="EnableTpl">
  <input type="checkbox" name="enable" value="{{d.id}},{{d.appname}}" lay-skin="switch" lay-text="启用|停用" lay-filter="wafRuleEnable" {{ d.enable == true ? 'checked' : '' }}>
</script>
<script>
    function getQueryString(name) {
      let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      let r = window.location.search.substr(1).match(reg);
      if (r != null) {
          return unescape(r[2]);
      };
      return null;
    };
    layui.use(['form', 'table'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;

//var stype = getQueryString("ruletype");

        table.render({
            elem: '#currentTableId',
            url: '/xwaf/rule/v1/List',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter'],
            cols: [[
                //{type: "checkbox", width: 50},
                {field: 'id',width:60,  title: 'ID', sort: true},
                {field: 'appname', title: '应用名'},
                {field: 'ruletype', title: '规则类型', sort: true},
                {field: 'ruleitem',width:'40%',edit:'text', title: '规则', sort: true},
                {field: 'enable',title:'状态',sort: true,templet: '#EnableTpl'},  
                {field: 'remarks',title: '备注',edit:'text'},
                {field: 'createtime', title: '创建时间'},
                {field: 'updatetime', title: '更新时间'},
                {title: '操作', minWidth:120, toolbar: '#currentTableBar', align: "center"}
            ]],
            limits: [25, 50, 100],
            limit: 15,
            page: true
        });

      //table里状态
      form.on('switch(wafRuleEnable)', function(data){
        var urls = location.search;
	      if (urls == "") {
		      urls = urls.replace("?", "&");
	      }
        var arry = this.value.split(',')
        var id = arry[0];
        var appname = arry[1];
        var bodystr = {"appname":appname,"name":this.name,"value":this.checked};
    			  $.ajax({
    			   url: "/xwaf/rule/v1/Edit?id=" + id + urls,
    			   headers:{'X-Requested-With':'XMLHttpRequest'},
             type: "POST",
             data: JSON.stringify(bodystr),
             dataType: "json",
    			   success: function (resp) {
    					  if (resp.code == 0 ) {
                  layer.msg('更改成功', {icon: 1});
                }else{
                  layer.msg(resp.msg,{icon:2});
                }
    				  }
    		    });
      });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var result = JSON.stringify(data.field);
            //layer.alert(result, {
            //    title: '最终的搜索信息'
            //});
            data.field.appname = data.field.appname.replace(/^\s*|\s*$/g,"");
            //执行搜索重载
            table.reload('currentTableId', {
                //page: {
                //    curr: 1,
                //    limit:50
                //},
                method:'POST',
                url: '/xwaf/rule/v1/List',
                contentType: 'application/json',
                where: data.field,
                done: function(res, curr, count){
                  //console.log(res);
                  //this.where={};
                  //不清空，有问题：搜索条件会保留
                  //清空，  有问题：分页的时候没有搜索条件了,分页会受到影响
                  //https://copyfuture.com/blogs-details/20200729003153292ltjtf01kvp048gr
                }
            }, 'data');

            return false;
        });

  	//监听单元格编辑
  	table.on('edit(currentTableFilter)', function(obj){
    	var value = obj.value //得到修改后的值
    	,datas = obj.data //得到所在行所有键值
    	,field = obj.field; //得到字段

      var bodystr = {"appname":datas.appname,"id":datas.id,"name":field,"value":value};
			      layer.confirm('确定修改?', {icon: 3, title:'提示',yes: function(index){
                 	$.ajax({
                     	//url: "/xwaf/rule/v1/Edit?id="+datas.id,
                     	url: "/xwaf/rule/v1/Edit" + location.search,
                      type: "POST",
                      data: JSON.stringify(bodystr),
                      dataType: "json",
                     	success: function (resp) {
                         	if(resp.code == 0){
                            	layer.msg('['+ datas.id +'] ' + field + '更改为:'+ value);
                         	}else{
                            	layer.msg('['+ datas.id +'] ' + field + '更改失败',{icon:2});
                         	}
                    	}
                	});	
              },
              cancel: function(index, layero){ 
                  layer.close(index);
              } 
            }); 	
  	});
    
  	table.on('toolbar(currentTableFilter)', function(obj){
    	//var checkStatus = table.checkStatus(obj.config.id);
    	switch(obj.event){
      		case 'Add':
					layer.open({
            			type:1,
						      skin: 'layui-layer-rim',
            			title:"添加规则",
            			area: ['50%', '70%'],
            			content:$("#AddRuleInfo").html()
                  //end: function(){
                  //	window.parent.location.reload();//关闭open打开的页面时，刷新父页面
                  //}
        	});
          //form.render('select');
          form.render();	
      		break;									
    	};
  	});
  
    //添加
    form.on('submit(Add)', function(datas){		
            datas.field.appname = datas.field.appname.replace(/^\s*|\s*$/g,""); //替换空格
            datas.field.ruleitem = datas.field.ruleitem.replace(/^\s*|\s*$/g,""); //替换空格
		       //console.log(JSON.stringify(datas.field));                         
			     layer.confirm('确定添加?', {icon: 3, title:'提示',yes: function(index){
                     $.ajax({
                       url: "/xwaf/rule/v1/Add"+location.search,
                       type: "post",
                       data: JSON.stringify(datas.field),
                       dataType: "json",
                       success: function (resp) {
					                //console.log(resp);
                           if(resp.code == 0){
                              layer.msg('添加成功', {icon: 1}); 
                           }else{
                              layer.msg('添加失败',{icon:2});
                           }
                        }
                     });		  	  
               },
                cancel: function(index, layero){ 
                    layer.close(index);
                } 
            }); 		   
	          return false; 	
		});	

        //监听表格复选框选择
        //table.on('checkbox(currentTableFilter)', function (obj) {
         //   console.log(obj)
        //});

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //暂时未用
                var index = layer.open({
                    title: '编辑',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: ['55%', '92%'],
                    content: '/xwaf/rule/edit.html?id='+data.Id,
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                //console.log(data);
                layer.confirm('确定删除'+data.id+'?', {icon: 3, title:'删除提示',yes: function(index){
                     var index2 = layer.load(0, {shade: false});
                     layer.msg('请稍等...');
                			 $.ajax({
                			    url: "/xwaf/rule/v1/Del?id="+data.id,
                			    type: "get",
                			    success: function (resp) {
                            layer.close(index2);

                						 if(resp.code == 0){
                							 layer.msg('删除成功', {icon: 1});
                							 //window.location.reload();
                							 obj.del();
                						 }else{
                							 layer.msg(resp.msg,{icon:2});
                						 }
                				  }
                		   });		  	  
                },
            		  cancel: function(index, layero){ 
            			    layer.close(index);
                      layer.close(index2);
            			    console.log("不操作");
            		  } 
        		    });                
            }
        });
    });
</script>
</html>